// Background service worker - Note: Tone.js cannot run in service workers
// Audio will be handled via message passing to content scripts or pages

// Import storage utilities
importScripts('../storage.js');

// Initialize on install
chrome.runtime.onInstalled.addListener(async () => {
  const data = await chrome.storage.local.get(['initialized']);
  
  if (!data.initialized) {
    await chrome.storage.local.set({ initialized: true });
  }
  
  await scheduleAllReminders();
  await fetchRSSFeed();
  
  chrome.alarms.create('rss-update', {
    delayInMinutes: 60,
    periodInMinutes: 360
  });
});

chrome.storage.onChanged.addListener(async (changes, areaName) => {
  if (areaName === 'local' && changes.reminders) {
    await scheduleAllReminders();
  }
});

async function scheduleAllReminders() {
  const alarms = await chrome.alarms.getAll();
  alarms.forEach(alarm => {
    if (alarm.name.startsWith('reminder-')) {
      chrome.alarms.clear(alarm.name);
    }
  });

  const data = await chrome.storage.local.get(['reminders', 'settings']);
  const reminders = data.reminders || [];
  const settings = data.settings || {};

  reminders.forEach(reminder => {
    if (reminder.enabled) {
      scheduleReminder(reminder, settings);
    }
  });
}

function scheduleReminder(reminder, settings) {
  const alarmName = `reminder-${reminder.id}`;
  chrome.alarms.clear(alarmName);

  if (reminder.timeOfDay) {
    const now = new Date();
    const [hours, minutes] = reminder.timeOfDay.split(':').map(Number);
    const scheduledTime = new Date();
    scheduledTime.setHours(hours, minutes, 0, 0);
    
    if (scheduledTime <= now) {
      scheduledTime.setDate(scheduledTime.getDate() + 1);
    }
    
    chrome.alarms.create(alarmName, {
      when: scheduledTime.getTime()
    });
  } else {
    const delayInMinutes = reminder.frequency || 60;
    chrome.alarms.create(alarmName, {
      delayInMinutes: delayInMinutes,
      periodInMinutes: delayInMinutes
    });
  }
}

chrome.alarms.onAlarm.addListener(async (alarm) => {
  if (alarm.name.startsWith('reminder-')) {
    const reminderId = alarm.name.replace('reminder-', '');
    await triggerReminder(reminderId);
  } else if (alarm.name === 'rss-update') {
    await fetchRSSFeed();
  }
});

async function triggerReminder(reminderId) {
  const data = await chrome.storage.local.get(['reminders', 'settings']);
  const reminders = data.reminders || [];
  const settings = data.settings || {};
  
  const reminder = reminders.find(r => r.id === reminderId);
  if (!reminder || !reminder.enabled) return;

  const updatedReminders = reminders.map(r => 
    r.id === reminderId ? { ...r, lastTriggered: Date.now() } : r
  );
  await chrome.storage.local.set({ reminders: updatedReminders });

  await trackReminderCompletion(reminder);

  // Send message to play sound using Tone.js in a page context
  // Pages will listen for this message and use audioManager
  chrome.runtime.sendMessage({
    action: 'playNotificationSound',
    soundType: settings.notificationSound || 'beep'
  }).catch(() => {});

  if (settings.notificationsEnabled !== false) {
    chrome.notifications.create({
      type: 'basic',
      iconUrl: 'icons/icon48.png',
      title: reminder.title,
      message: reminder.description || `Time for: ${reminder.title}`,
      priority: 1
    });
  }

  if (settings.badgeEnabled !== false) {
    const badgeData = await chrome.storage.local.get('badgeCount');
    const currentCount = badgeData.badgeCount || 0;
    await chrome.storage.local.set({ badgeCount: currentCount + 1 });
    chrome.action.setBadgeText({ text: String(currentCount + 1) });
    chrome.action.setBadgeBackgroundColor({ color: '#4CAF50' });
  }

  scheduleReminder(reminder, settings);
}

async function trackReminderCompletion(reminder) {
  try {
    const gamificationData = await chrome.storage.local.get('gamification');
    const gamification = gamificationData.gamification || {
      stats: { hydrationCompleted: 0, remindersCompleted: 0 }
    };
    
    const stats = gamification.stats || {};
    stats.remindersCompleted = (stats.remindersCompleted || 0) + 1;
    
    if (reminder.category === 'Hydration') {
      stats.hydrationCompleted = (stats.hydrationCompleted || 0) + 1;
    }
    
    gamification.stats = stats;
    await chrome.storage.local.set({ gamification });
  } catch (error) {
    console.error('Error tracking reminder completion:', error);
  }
}

chrome.notifications.onClicked.addListener((notificationId) => {
  chrome.notifications.clear(notificationId);
  chrome.tabs.create({ url: chrome.runtime.getURL('newtab.html') });
});

chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  if (request.action === 'clearBadge') {
    chrome.action.setBadgeText({ text: '' });
    chrome.storage.local.set({ badgeCount: 0 });
  } else if (request.action === 'reminderDue') {
    handleReminderDue(request.reminder);
    sendResponse({ success: true });
  } else if (request.action === 'fetchRSS') {
    fetchRSSFeed().then(() => {
      sendResponse({ success: true });
    }).catch((error) => {
      sendResponse({ success: false, error: error.message });
    });
    return true;
  }
  return true;
});

async function handleReminderDue(reminder) {
  if (!reminder || !reminder.enabled) return;
  
  const settings = await chrome.storage.local.get('settings');
  const userSettings = settings.settings || {};
  
  chrome.runtime.sendMessage({
    action: 'playNotificationSound',
    soundType: userSettings.notificationSound || 'beep'
  }).catch(() => {});
  
  if (userSettings.notificationsEnabled !== false) {
    chrome.notifications.create({
      type: 'basic',
      iconUrl: 'icons/icon48.png',
      title: reminder.title,
      message: reminder.description || `Time for: ${reminder.title}`,
      priority: 2
    });
  }
  
  if (userSettings.badgeEnabled !== false) {
    const badgeData = await chrome.storage.local.get('badgeCount');
    const currentCount = badgeData.badgeCount || 0;
    await chrome.storage.local.set({ badgeCount: currentCount + 1 });
    chrome.action.setBadgeText({ text: String(currentCount + 1) });
    chrome.action.setBadgeBackgroundColor({ color: '#4CAF50' });
  }
}

// RSS Feed Functions
const RSS_FEED_URL = 'https://www.lifespan.io/feed/';

function decodeHTML(text) {
  if (!text) return '';
  return text
    .replace(/&nbsp;/g, ' ')
    .replace(/&amp;/g, '&')
    .replace(/&lt;/g, '<')
    .replace(/&gt;/g, '>')
    .replace(/&quot;/g, '"')
    .replace(/&#39;/g, "'")
    .replace(/&#x27;/g, "'")
    .replace(/&#8217;/g, "'")
    .replace(/&#8211;/g, '–')
    .replace(/&#8212;/g, '—')
    .replace(/&#8230;/g, '…')
    .replace(/&apos;/g, "'")
    .replace(/&#039;/g, "'")
    .replace(/&#x2F;/g, '/')
    .replace(/&#x60;/g, '`')
    .replace(/&#x3D;/g, '=');
}

async function fetchRSSFeed() {
  try {
    const response = await fetch(RSS_FEED_URL);
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    const xmlText = await response.text();
    const articles = parseRSSFeed(xmlText);
    
    await chrome.storage.local.set({
      rssArticles: articles,
      rssLastUpdate: Date.now()
    });
    
    console.log(`RSS feed updated: ${articles.length} articles`);
  } catch (error) {
    console.error('Error fetching RSS feed:', error);
  }
}

function parseRSSFeed(xmlText) {
  const articles = [];
  
  const itemRegex = /<item[^>]*>([\s\S]*?)<\/item>/gi;
  const items = xmlText.match(itemRegex);
  
  if (!items || items.length === 0) {
    console.error('No RSS items found');
    return articles;
  }
  
  items.forEach((itemXml, index) => {
    const titleMatch = itemXml.match(/<title[^>]*>([\s\S]*?)<\/title>/i);
    const title = titleMatch ? extractTextContent(titleMatch[1]) : '';
    
    const linkMatch = itemXml.match(/<link[^>]*>([\s\S]*?)<\/link>/i);
    const link = linkMatch ? extractTextContent(linkMatch[1]).trim() : '';
    
    const descMatch = itemXml.match(/<description[^>]*>([\s\S]*?)<\/description>/i);
    const description = descMatch ? extractTextContent(descMatch[1]) : '';
    
    const pubDateMatch = itemXml.match(/<pubDate[^>]*>([\s\S]*?)<\/pubDate>/i);
    const pubDate = pubDateMatch ? extractTextContent(pubDateMatch[1]).trim() : '';
    
    const categoryRegex = /<category[^>]*>([\s\S]*?)<\/category>/gi;
    const categoryMatches = itemXml.match(categoryRegex);
    const categories = categoryMatches 
      ? categoryMatches.map(match => {
          const catText = match.replace(/<\/?category[^>]*>/gi, '');
          return extractTextContent(catText).trim();
        }).filter(cat => cat.length > 0)
      : [];
    
    let imageUrl = '';
    const mediaContentMatch = itemXml.match(/<media:content[^>]*url=["']([^"']+)["'][^>]*>/i) ||
                              itemXml.match(/<content[^>]*url=["']([^"']+)["'][^>]*>/i);
    if (mediaContentMatch) {
      imageUrl = mediaContentMatch[1];
    }
    
    if (!imageUrl) {
      const enclosureMatch = itemXml.match(/<enclosure[^>]*url=["']([^"']+)["'][^>]*type=["']([^"']+)["'][^>]*>/i);
      if (enclosureMatch && enclosureMatch[2]?.startsWith('image/')) {
        imageUrl = enclosureMatch[1];
      }
    }
    
    const cleanDescription = decodeHTML(description)
      .replace(/<[^>]*>/g, '')
      .trim()
      .substring(0, 200);
    
    const cleanTitle = decodeHTML(title).trim();
    
    if (cleanTitle) {
      articles.push({
        id: `rss-${Date.now()}-${index}`,
        title: cleanTitle,
        link: link,
        description: cleanDescription,
        pubDate: pubDate,
        categories: categories,
        imageUrl: imageUrl,
        source: 'Lifespan.io',
        timestamp: Date.now()
      });
    }
  });
  
  return articles;
}

function extractTextContent(text) {
  if (!text) return '';
  text = text.replace(/<!\[CDATA\[([\s\S]*?)\]\]>/gi, '$1');
  return decodeHTML(text);
}

setInterval(async () => {
  const data = await chrome.storage.local.get(['reminders', 'settings']);
  const reminders = data.reminders || [];
  const settings = data.settings || {};
  
  const now = Date.now();
  const checkedReminders = await chrome.storage.local.get('checkedReminders');
  const lastChecked = checkedReminders.checkedReminders || {};
  
  reminders.forEach(reminder => {
    if (!reminder.enabled || !reminder.lastTriggered) return;
    
    const frequencyMs = reminder.frequency * 60 * 1000;
    const nextTriggerTime = reminder.lastTriggered + frequencyMs;
    const timeRemaining = nextTriggerTime - now;
    
    const reminderKey = reminder.id;
    const wasDue = lastChecked[reminderKey] || false;
    const isDue = timeRemaining <= 0;
    
    if (!wasDue && isDue) {
      handleReminderDue(reminder);
      lastChecked[reminderKey] = true;
    } else if (wasDue && !isDue) {
      lastChecked[reminderKey] = false;
    }
  });
  
  await chrome.storage.local.set({ checkedReminders: lastChecked });
}, 2000);

